import { safeIndexApi } from '@/api';
import { YmResponseCode } from '@/api/request/core';
import CusModal from '@/components/CusModal';
import YmCollaPanes from '@/components/YmCollaPanes';
import { NoListDom } from '@/pages/Statistics/LearningStatistics/NoListDom';
import { App, Button, message, Spin } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { YmAddPageLayout, type YmAddPageLayoutProps } from 'ym-design';
import AddOrEditFactorForm from './AddOrEditFactorForm';
import AddOrEditMatterForm from './AddOrEditMatterForm';
import HeaderTitle from './HeaderTitle';
import OStyle from './index.less';
import { AboutCarProps } from './interface';
import QueTable from './QueTable';
import SimpleFormulaSet from './SimpleFormulaSet';
const { PaneItem } = YmAddPageLayout;

const AboutCmp: React.FC<AboutCarProps> = (props) => {
  const { pageType } = props; // 1车辆相关  2司机相关  3驾驶行为
  const {
    modal: { confirm },
  } = App.useApp();
  const [contLoading, setContLoading] = useState(true);
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([0, 1, 2, 3]);
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string; modelType?: string }>({ show: false });
  // const [isFactorShow, setIsFactorShow] = useState<boolean>(false);
  const [totalScore, setTotalScore] = useState<any>(0);
  const [aboutCarList, setAboutCarList] = useState<any[]>([]); // 事项列表
  // const [modalType, setModalType] = useState<string>(''); // 弹窗类型
  const addOrEditFolderRef = useRef<any>(null);
  const addOrEditFactorRef = useRef<any>(null);
  const addSimpleRef = useRef<any>(null);
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态

  // 新增/编辑因子
  const addEditFactor = (record: any) => {
    const { type } = record;
    setIsModalShow({ show: true, type, modelType: 'matter' });
    setConfigModal({
      title: type == 'add' ? '新增因子' : '修改因子',
      children: <AddOrEditFactorForm ref={addOrEditFactorRef} {...record} pageType={pageType} />,
    });
  };
  const getMatterList = () => {
    setContLoading(true);
    safeIndexApi.getMatterGropList({ relatedType: pageType }).then((res: any) => {
      setAboutCarList(res.data);
      let score = 0;
      res.data.forEach((el: any) => {
        score = score + +el.groupScore;
      });
      setTotalScore(score.toFixed(2));
      setContLoading(false);
    });
  };
  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };
  const titleCont = (
    <div>
      删除<span style={{ color: 'red', fontSize: 12 }}>（请谨慎删除，或将影响相关安全指数）</span>
    </div>
  );
  // 删除因子
  const handleSchoiceQuestionsRemove = (record: any) => {
    const { factorId, factorName } = record;
    confirm({
      title: titleCont,
      content: `确定删除因子 ${factorName}吗？`,
      centered: true,
      onOk: () => {
        safeIndexApi.delFactor({ factorId: factorId }).then((res) => {
          const { code, msg } = res;
          code === YmResponseCode.normal ? message.success(msg) : message.error(msg);
          getMatterList();
          // closeModal();
        });
      },
    });
  };
  // 新建、编辑 事项 接口
  const addOrEditMatterApi = (values: any) => {
    const { groupName, type, groupId } = values;
    const param = { relatedType: pageType, groupName };
    const requestApi =
      type === 'add' ? safeIndexApi.addMatterGroup({ ...param }) : safeIndexApi.editMatterGroup({ groupId, ...param });
    requestApi.then((res: any) => {
      if (res) {
        message.success('操作成功!');
        getMatterList();
        closeModal();
      }
    });
  };
  // 新增/编辑 因子 接口
  const addOrEditFactorApi = (values: any) => {
    // const { groupName, type, groupId } = values;
    const { type, factorId } = values;
    // const param = { relatedType: 1, groupName };
    const { type: _, ...param } = values;
    console.log(_);
    const requestApi =
      type === 'add' ? safeIndexApi.addFactor({ ...param }) : safeIndexApi.editFactor({ factorId, ...param });
    requestApi.then((res: any) => {
      if (res) {
        message.success('操作成功!');
        getMatterList();
        closeModal();
      }
    });
  };
  // 设置简单计算规则 接口
  const addOrEditSimpleApi = (values: any) => {
    const { maximumScore, factorId } = values;
    const param = { maximumScore: maximumScore, factorId };
    safeIndexApi.setSimpRules({ ...param }).then((res: any) => {
      console.log(res, '打印看看啥东东');
      if (res.code == 200) {
        message.success('操作成功!');
        getMatterList();
        closeModal();
      }
    });
  };
  //点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    if (addOrEditFactorRef.current) {
      // if (isModalShow.type === 'add') {
      addOrEditFactorRef.current
        ?.onSubmit()
        .then((values: any) => {
          if (!values) return;
          addOrEditFactorApi(values);
        })
        .finally(() => {
          setModalBtnStatus({ disabled: false, loading: false });
        });
      // }
    } else if (addOrEditFolderRef.current) {
      // if (isModalShow.type === 'add') {
      addOrEditFolderRef.current
        ?.onSubmit()
        .then((values: any) => {
          if (!values) return;
          addOrEditMatterApi(values);
        })
        .finally(() => {
          setModalBtnStatus({ disabled: false, loading: false });
        });
      // }
    } else if (addSimpleRef.current) {
      addSimpleRef.current
        ?.onSubmit()
        .then((values: any) => {
          if (!values) return;
          addOrEditSimpleApi(values);
        })
        .finally(() => {
          setModalBtnStatus({ disabled: false, loading: false });
        });
    }
    setModalBtnStatus({ disabled: false, loading: false });
  };
  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 520,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        保存
      </Button>,
    ],
    onCancel: closeModal,
  };
  const addMatter = (param: any) => {
    const { type } = param;
    // setModalType('matter');
    setIsModalShow({ show: true, type, modelType: 'matter' });
    setConfigModal({
      title: type === 'add' ? '新增事项' : '修改事项',
      children: <AddOrEditMatterForm ref={addOrEditFolderRef} {...param} />,
    });
  };
  // 打开简单规则弹窗
  const addSimple = (param: any) => {
    console.log(param, '打印看看');
    const { type } = param;
    setIsModalShow({ show: true, type, modelType: 'simple' });
    setConfigModal({
      title: type === 'add' ? '添加简单规则' : '设置简单规则',
      children: <SimpleFormulaSet ref={addSimpleRef} {...param} />,
    });
  };
  // 删除事项
  const removeMatter = (param: any) => {
    const { groupId, scoreTypeName } = param;
    confirm({
      title: titleCont,
      content: `确定删除事项 ${scoreTypeName}吗？`,
      centered: true,
      onOk: () => {
        safeIndexApi.delMatterGroup({ groupId: groupId }).then((res) => {
          const { code, msg } = res;
          code === YmResponseCode.normal ? message.success(msg) : message.error(msg);
          getMatterList();
          // closeModal();
        });
      },
    });
  };
  const operationFooter = useMemo(() => {
    const operationBtn = [
      <div key="totalScore" className={OStyle.row_number}>
        <div style={{ width: 42 }}> 满分：</div>
        <span className={OStyle.number_bold}>{totalScore}</span>分
      </div>,
      <Button
        key="subOnce"
        type="primary"
        size="small"
        onClick={() => {
          addMatter({ type: 'add' });
        }}
      >
        新增事项
      </Button>,
    ];
    return operationBtn;
  }, [totalScore]);

  useEffect(() => {
    getMatterList();
  }, []);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        operationDom: <></>,
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={(pageType == 1 ? '车辆' : pageType == 2 ? '司机' : '驾驶行为') + '相关因子设置'}
        className="pane_tab1"
      >
        <div style={{ background: '#fff', width: '100%' }}>
          <div className={OStyle.cont_main}>
            <Spin spinning={contLoading} style={{ minHeight: 400 }}>
              {aboutCarList.length > 0 ? (
                <>
                  {aboutCarList.map((el, index) => {
                    return (
                      <YmCollaPanes
                        key={index}
                        collPanesActiveKeys={collPanesActiveKeys}
                        paneKey={1}
                        collapsible={false}
                        headerTitle={
                          <HeaderTitle
                            scoreTypeName={el.groupName}
                            score={el.groupScore}
                            scoreLength={4}
                            groupId={el.groupId}
                            onRemoveMatter={removeMatter}
                            onEditMatter={() => {
                              addMatter({ type: 'edit', groupId: el.groupId, groupName: el.groupName });
                            }}
                          />
                        }
                      >
                        <div className={OStyle.pane_content_body}>
                          <QueTable
                            scoreTypeName={el.groupName}
                            questions={el.safetyFactorDetailVoList || []}
                            onAddQuestion={() => {
                              //   setSChoiceQueScoreDetail((prev) => ({ ...prev, modalOpen: Math.random() }));
                            }}
                            onQuestionsRemove={handleSchoiceQuestionsRemove}
                            onAddOrEditfactor={addEditFactor}
                            onSetSimpleRules={addSimple}
                            onRefresh={getMatterList}
                            pageType={pageType}
                          />
                        </div>
                      </YmCollaPanes>
                    );
                  })}
                </>
              ) : (
                <NoListDom></NoListDom>
              )}
            </Spin>
          </div>

          <CusModal {...modalConst} {...configModal} />
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
};

export default AboutCmp;
